import React from 'react';
import { RouteObject } from 'react-router-dom';

// 菜单项接口
interface MenuItem {
    index: string;
    title: string;
    path?: string;
    name?: string;
    component?: string;
    type?: string;
    menuType?: number;
    meta?: Record<string, any>;
    children?: MenuItem[];
}

// 动态加载组件
const loadComponent = (component: string) => {
    const Comp = React.lazy(() => import(`../pages/${component}`));
    return Comp;
};

// 添加动态路由
const addDynamicRoutes = (
    menus: MenuItem[],
    routes: RouteObject[]
): RouteObject[] => {
    // 查找Layout路由
    const layoutRoute = routes.find((route) => route.path === '/');

    if (!layoutRoute || !layoutRoute.children) {
        console.error('Layout route not found');
        return routes;
    }

    // 处理菜单项
    menus.forEach((menu) => {
        if (menu.children) {
            menu.children.forEach((child) => {
                try {
                    // 只处理有效的路由菜单项
                    if (child.path && child.component) {
                        // 处理路径中可能的转义字符
                        const cleanPath = child.path.replace(/\\\//g, '/');
                        
                        // 构建路由配置
                        const Component = loadComponent(child.component);
                        const routeConfig = {
                            path: cleanPath.replace(/^\//, ''), // 移除开头的斜杠
                            element: React.createElement(Component),
                        };

                        // console.log(`Adding route: ${routeConfig.path} => ${child.component}`);

                        // 添加到Layout的子路由
                        layoutRoute.children?.push(routeConfig);
                    }
                } catch (error) {
                    console.error(`Failed to load component: ${child.component}`, error);
                }
            });
        }
    });

    return routes;
};

export default addDynamicRoutes;